<template>
  <el-card>
    <el-form>
      <el-form-item label="角色名称">
        <el-input disabled :value="$route.query.roleName" />
      </el-form-item>
      <el-form-item label="权限列表">
        <el-tree
          ref="treeRef"
          :data="rolePermissionList"
          show-checkbox
          node-key="id"
          default-expand-all
          :props="{
            children: 'children',
            label: 'name',
          }"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="confirm">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "roleAuth",
};
</script>

<script lang="ts" setup>
import { ref, onActivated } from "vue";
import { getRolePermissionApi, distributePermissionApi } from "@/api/acl/role";
import type { GetRolePermissionList } from "@/api/acl/model/roleModel";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
const treeRef = ref();
const route = useRoute();
const rolePermissionList = ref<GetRolePermissionList>([]);
// 获取选中的id(只要最后一层的id)
const getCheckedKeys = (rolePermissionList: GetRolePermissionList) => {
  let checkedKeys: string[] = [];
  rolePermissionList.forEach((rolePermission) => {
    // 还有子分支
    if (rolePermission.children.length) {
      const newCheckedKeys = getCheckedKeys(rolePermission.children);
      checkedKeys = [...checkedKeys, ...newCheckedKeys];
    }
    // 没有子分支并且选中
    else if (rolePermission.select) {
      checkedKeys.push(rolePermission.id);
    }
  });
  return checkedKeys;
};
// 激活的时候发送请求
onActivated(async () => {
  const res = await getRolePermissionApi(route.query.id as string);
  rolePermissionList.value = res.children;
  // 获取由id组成的选中项的数组
  const checkedKeys = getCheckedKeys(res.children);
  // 设置目前选中的节点
  treeRef.value.setCheckedKeys(checkedKeys);
});
// 保存按钮
const confirm = async () => {
  const setRolePermissionList = [
    ...treeRef.value.getCheckedKeys(),
    ...treeRef.value.getHalfCheckedKeys(),
  ];
  await distributePermissionApi(
    route.query.id as string,
    setRolePermissionList
  );
  ElMessage.success("权限分配成功!");
  cancel();
};
// 取消按钮
const router = useRouter();
const cancel = () => {
  router.push({
    name: "Role",
  });
};
</script>

<style scoped>
:deep(.el-tree__empty-block) {
  width: 1100px;
}
</style>
